const Service = require("egg").Service;
const fs = require("fs-extra");
const p = require("path");
const sequelize = require("sequelize");
const _ = require("loadsh");
var qs = require("qs");
const needle = require("needle");

class FilmService extends Service {
  async lastAdd(params) {
    let tvRet = await this.ctx.model.Teleplay.findAll({
      order: [["created_at", "DESC"]],
      where: {
        show: true,
      },
      limit: 8,
      offset: 0,
    });
    let movieRet = await this.ctx.model.Movie.findAll({
      order: [["created_at", "DESC"]],
      where: {
        show: true,
      },
      limit: 8,
      offset: 0,
    });
    let ret = tvRet
      .map(a => ({ ...a, type: "tv" }))
      .concat(movieRet.map(a => ({ ...a, type: "movie" })))
      .sort((a, b) => new Date(b.created_at) - new Date(a.created_at));
    return { data: { rows: ret }, msg: "获取电影数据预设成功" };
  }
  async recommendRandom() {
    let tvCount = await this.ctx.model.Teleplay.count();
    let movieCount = await this.ctx.model.Movie.count();
    let tvRandomArr = Array(10)
      .fill(1)
      .map(a => Math.floor(Math.random() * tvCount));
    tvRandomArr = Array.from(new Set(tvRandomArr));
    let movieRandomArr = Array(10)
      .fill(1)
      .map(a => Math.floor(Math.random() * movieCount));
    movieRandomArr = Array.from(new Set(movieRandomArr));
    let rows = [];
    for (let itm of tvRandomArr) {
      let tmp = await this.ctx.model.Teleplay.findByPk(itm);
      if(tmp==undefined){
        continue;
      }
      if (tmp.show == 0) {
        continue;
      }
      rows.push({...tmp, type:'tv'});
    }
    for (let itm of movieRandomArr) {
      let tmp = await this.ctx.model.Movie.findByPk(itm);
      if(tmp==undefined){
        continue;
      }
      if (tmp.show == 0) {
        continue;
      }
      rows.push({...tmp, type:'movie'});
    }
    return { data: { rows } };
  }
  async doubanSearch(params) {
    console.log(params);
    let url =
      `https://search.douban.com/movie/subject_search?` +
      qs.stringify({ search_text: params.value });
    console.log(url);
    try {
      let page = await this.app.browser.newPage();
      await page.setUserAgent(
        "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/85.0.4183.83 Safari/537.36 Edg/85.0.564.41"
      );
      await page.goto(url, { waitUntil: "networkidle0" });
      let nodeList = await page.$$(".item-root");
      if (nodeList.length < 1) {
        return { msg: "没有找到资源，请更换关键词重试~", code: 400 };
      }
      if (nodeList.length > 8) {
        nodeList.length = 8;
      }
      let ret = [];
      for (let node of nodeList) {
        let name =
          (await node
            .$eval(".title-text", el => el.innerText)
            .catch(e => {})) ?? "";
        console.log(name);
        let href =
          (await node.$eval(".cover-link", el => el.href).catch(e => {})) ?? "";
        let score =
          (await node
            .$eval(".rating_nums", el => el.innerText)
            .catch(e => {})) ?? "";

        let pic =
          (await node
            .$eval(".cover", async el => el.src)
            .catch(e => {
              console.log(e);
            })) ?? "";
        let abstract =
          (await node.$eval(".abstract", el => el.innerText).catch(e => {})) ??
          "";
        let abstract2 =
          (await node
            .$eval(".abstract_2", el => el.innerText)
            .catch(e => {})) ?? "";
        ret.push({
          name,
          pic,
          abstract,
          abstract2,
          href,
          score,
          loading: false,
          score_2: score == "" ? 0 : (Number(score) / 2).toFixed(1),
        });
      }
      await page.close();
      return { data: ret };
    } catch (e) {
      console.log(e);
    }
  }
  async getDoubanItem(params) {
    console.log(params);
    let page = await this.app.browser.newPage();
    await page.setUserAgent(
      "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/85.0.4183.83 Safari/537.36 Edg/85.0.564.41"
    );
    await page.goto(params.href, { waitUntil: "networkidle0" });
    let name =
      (await page
        .$eval("#content > h1 > span", el => el.innerText)
        .catch(e => {})) ?? "";
    let pic =
      (await page.$eval(".nbgnbg > img ", el => el.src).catch(e => {})) ?? "";
    let directors =
      (await page
        .evaluate(() => {
          let arr = [];
          $("#info .attrs a[rel='v:directedBy']").each(function () {
            arr.push(this.innerText);
          });
          return arr.join("/");
        })
        .catch(e => {})) ?? "";
    let actors =
      (await page
        .$eval("#info > .actor > .attrs", el => el.innerText)
        .catch(e => {})) ?? "";
    actors = actors
      .split("/")
      .filter(a => a.indexOf("更多") == -1)
      .map(a => a.trim())
      .join("/");
    let classify =
      (await page
        .evaluate(() => {
          let arr = [];
          $("#info span[property='v:genre']").each(function () {
            let str = this.innerText;
            if (str == "真人秀") {
              str = "综艺";
            }
            if (str == "动画") {
              str = "动漫";
            }
            arr.push(str);
          });
          return arr.join("/");
        })
        .catch(e => {})) ?? "";
    let score =
      (await page.$eval(".rating_num", el => el.innerText).catch(e => {})) ??
      "";
    let desc =
      (await page
        .$eval("#link-report-intra > span", el => el.innerText)
        .catch(e => {})) ?? "";
    let ret = {
      name,
      directors,
      actors,
      classify,
      score,
      desc: desc.trim(),
      pic,
    };
    return { data: ret };
  }
}

module.exports = FilmService;
